package com.yoso.service.jpa;

import com.querydsl.core.Tuple;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.yoso.domain.jpa.UserEntity;
import com.yoso.domain.jpa.qentity.QOrderEntity;
import com.yoso.domain.jpa.qentity.QUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import java.util.List;

/**
 * @author shizejin
 * @date 2022/8/8
 * @description:
 */
@Service
public class UserDslService {

    private JPAQueryFactory queryFactory;
    @Autowired
    private EntityManager entityMapper;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityMapper);
    }

    public List<UserEntity> listByName(String name) {
        QUserEntity qUserEntity = QUserEntity.userEntity;
        QOrderEntity qOrderEntity = QOrderEntity.orderEntity;
        BooleanExpression yoso = qUserEntity.name.eq(name);
        List<Tuple> tupleList = queryFactory
                .select(qUserEntity.age.as("age"), qOrderEntity.buyerName.as("buyerName"))
                .from(qUserEntity)
                .where(yoso)
                .leftJoin(qOrderEntity)
                .on(qUserEntity.name.eq(qOrderEntity.buyerName))
                .offset(0)
                .limit(2)
                .orderBy(qUserEntity.age.asc())
                .fetch();
        for (Tuple tuple : tupleList) {
            String s = tuple.toString();
            System.out.println("s = " + s);
        }
        return null;
    }

}
